package cn.uway.netty.server;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerHandler extends ChannelInboundHandlerAdapter{
	
	private static Logger logger = LoggerFactory.getLogger(ServerHandler.class);
	
    @Override  
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {  
        super.handlerAdded(ctx); 
        logger.debug("{} incomeing....", ctx.channel());
        Channel channel = ctx.channel();
        
        logger.debug("===========客户端建立一个连接：{},remoteAddress={} ",channel, ctx.channel().remoteAddress().toString());
    }  
    
    public  boolean isLocalConnect( Channel channel ){
    	
    	String localAddress = channel.localAddress().toString();
    	String remoteAddress = channel.remoteAddress().toString();
    	//return remoteAddress.contains("127.0.0.1") || remoteAddress.contains("localhost");
    	
    	String remoteIp =  remoteAddress.substring(0, remoteAddress.lastIndexOf(":") ) ;
    	if(remoteIp.startsWith("/")){
    		remoteIp = remoteIp.substring(1);
    	}
    	
    	String localIp =  localAddress.substring(0, localAddress.lastIndexOf(":") ) ;
    	if(localIp.startsWith("/")){
    		localIp = localIp.substring(1);
    	}
    	
    	logger.debug("===========isLocalConnect, localIp={} , remoteIp={}", localIp, remoteIp );
    	return localIp.equals(remoteIp);    	
    }
  
    @Override  
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {  
        super.handlerRemoved(ctx); 
        logger.debug("{} out of....", ctx.channel());        
    }  
  
    @Override  
    public void channelRead(ChannelHandlerContext ctx, Object msg)  
            throws Exception { 
    	logger.debug("ServerHandler  channel {} 接收到的报文内容为：{}", ctx.channel(), msg);    	
    	String txtContent = (String) msg;
    	logger.debug("ServerHandler 接收到的报文为：{} ", txtContent); 
    	//应答
		String respStr = "ok\r\n";
		ByteBuf resp = Unpooled.copiedBuffer(respStr.getBytes());
        ctx.writeAndFlush(resp);   	        
    }  
  
    @Override  
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {  
        ctx.flush();  
    }  
  
    @Override  
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)  
            throws Exception {  
    	if(cause instanceof java.io.IOException){ 
    	   String msg = cause.getMessage();
    	   if(msg.contains("远程主机强迫关闭了一个现有的连接")){
    		   ctx.channel().close();
    		   ctx.close();
    	   }
    	   else if(msg.contains("中止了一个已建立的连接") ){
    		   logger.info(msg);    
    	   }
    	   else{
    		   logger.error("handler捕获到异常", cause);    
    	   }    			
    	}
    	else{
    		logger.error("handler捕获到异常", cause);    	
    	}
    	
    }
    
      
   
}
